<template>
  <el-form size="small" :model="searchForm" label-width="0px" class="m-t-15">
          <el-form-item>
            <el-button v-for="(item,index) in initData.areas" :key="index" size="small" :type="searchForm.areas == item.value ? 'primary' : 'default'" class="wd-60" @click="changeAreas(item.value)">
              {{ item.label }}
            </el-button>
          </el-form-item>
          <el-form-item v-if="searchForm.areas > 0">
            <el-checkbox :indeterminate="indeterminate" v-model="isCheckedAll" @change="changeCheckAll">全选</el-checkbox>
            <el-checkbox-group v-model="initData.stationsChecked" @change="changeStations">
              <el-checkbox v-for="(item,index) in initData.stations" :key="index" :label="item.id" >{{item.name}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item>
            <el-select v-model="searchForm.county" placeholder="请选择" style="width:100%;" @change="handleFilter">
              <el-option v-for="(item,index) in initData.countys" :key="index" :label="item.name" :value="item.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="form-class">
            <el-checkbox-group v-model="searchForm.class" @change="changeClass">
              <el-checkbox v-for="(item,index) in initData.classes" :key="index" :label="item.label" >
                <!-- <img :src="item.icon" width="16px" class="fl m-r-5" /> -->
                <span class="dot" :style="{background:item.color}"></span>
                {{item.label}}
            </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item class="height-auto" v-if="searchForm.class.indexOf('工业源') != -1">
            <el-checkbox :indeterminate="indeterminateIndustries" v-model="checkedAllIndustries" @change="changeCheckAllIndustries">全选</el-checkbox>
            <el-select
              v-model="searchForm.industries"
              multiple
              collapse-tags
              class="select-industries"
              style="margin-left: 0px;height:auto;width:100%;"
              placeholder="请选择"
              @change="changeIndustries">
              <el-option
                v-for="item in initData.industries"
                :key="item.id"
                :label="item.text"
                :value="item.text">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input placeholder="输入污染源名称" v-model="searchForm.searchText" clearable class="btn-search">
              <el-button slot="append" icon="el-icon-search" size="small" type="primary" @click="handleFilter"></el-button>
            </el-input>
          </el-form-item>
        </el-form>
</template>
<script>
import mapboxgl from 'mapbox-gl';
import {city,cityId,cityPinyin,geoserver} from '@/config/env';

export default {
  data(){
    return {
      searchForm:{
        industries:[],
        areas: 0,
        county: '全市',
        class: [],
        sattion_id: 0,
        searchText: null,
      },
      isCheckedAll: true,
      indeterminate: false,
      checkedAllIndustries: true,
      indeterminateIndustries: false,
      initData:{
        allIndustries: [],
        industries: [],
        areas : [
          { label: '不限', value: 0 },
          { label: '1公里', value: 1 },
          { label: '3公里', value: 3 },
          { label: '5公里', value: 5 },
        ],
        stations: [],
        countys: [
          {name: '全市', value: ''},
          {name: '香洲区', value: ''},
          {name: '金湾区', value: ''},
          {name: '斗门区', value: ''},
          {name: '高新区', value: ''},
          {name: '鹤洲新区', value: ''},
          {name: '横琴粤澳深度合作区', value: ''}
        ],
        classes:[
        { label: '工业源', value: 1, name: 'industry',color: '#FE5656', icon: require('@/assets/images/icons/工业源.png') },
          { label: '扬尘源', value: 2, name: 'dust',color: '#EAEA26', icon: require('@/assets/images/icons/扬尘源.png')},
          { label: '油站油库', value: 3, name: 'oil',color: '#01E17E', icon: require('@/assets/images/icons/油站油库.png') },
          { label: '大型餐饮', value: 4, name: 'restaurant',color: '#3DD1F9', icon: require('@/assets/images/icons/大型餐饮.png') },
        ],
        stationsChecked: [],
        location: [],
      },
      layer:{
        stations_inventory: 'stations_inventory_' + cityPinyin,
        stations_inventory_circle: 'stations_inventory_circle_'+cityPinyin
      },
      map: null,
    }
  },
  created() {
    // this.getInitData();
  },
  methods:{
    async getInitData(){
      this.searchForm.class = this.initData.classes.map(item => item.label);
      this.initData.stations = await this.$request('get', '/air/stations', {});    
      this.initData.stationsChecked = this.initData.stations.map(item => item.id);  
      let allIndustries = await this.$request('get', '/stations/ind_code', {});
      this.getIndustries(allIndustries);
    },
    getIndustries(allIndustries){
      this.initData.allIndustries = allIndustries;    
      let newIndustries = allIndustries.map(item => {
        item.label = item.value + ' | ' + item.text;
        return item;
      });
      this.initData.industriesTree = this.$util.getTreeList(newIndustries, {
        parentId: 'parent_id'
      });
      this.initData.industriesTree = this.changeTree(this.initData.industriesTree);
      let industries = [];
      this.initData.industriesTree.forEach(item => {
        industries = industries.concat(item.children);
      });
      this.initData.industries = industries.filter(item => {
        return Number(item.value) > 4 && Number(item.value) < 47;
      });
      this.searchForm.industries = this.initData.industries.map(item => item.text);
    },
    changeTree(data){
      let arr = data.map(item => {
        if(!item.hasOwnProperty('children')){
          item.label = item.value4 + ' | ' + item.text;
        }else{
          item.children = this.changeTree(item.children);
        };
        return item;
      });
      return arr;
    },
    changeAreas(val){
      this.searchForm.areas = val;
      this.addCircleLayer();
      this.addInventoryLayer();
      this.addInventoryCircleLayer(true);
    },
    changeCounty(val){
      let obj = this.initData.countys.find(item => item.id == val);
    },
    changeClass(val){
      if(val.indexOf('工业源') == -1){
        this.searchForm.industries = this.initData.industries.map(item => item.text);
        this.indeterminateIndustries = false;
      }
      this.addCircleLayer();
      this.addInventoryLayer();
      this.addInventoryCircleLayer();
    },
    changeCheckAll(val){
      let arr = [];
      if(val){
        arr = this.initData.stations.map(item => item.id);
        this.indeterminate = false;
      }
      this.initData.stationsChecked = arr;     
      this.addCircleLayer();
      this.addInventoryCircleLayer(true);
    },
    changeCheckAllIndustries(val){
      let arr = [];
      if(val){
        arr = this.initData.industries.map(item => item.text);
        this.indeterminateIndustries = false;
      }
      this.searchForm.industries = arr;    
      // this.addCircleLayer();
      this.addInventoryLayer();
      this.addInventoryCircleLayer();
    },
    changeIndustries(val){
      let len = this.initData.industries.length;
      let n = val.length;
      if(n == 0){
        this.checkedAllIndustries = false;
        this.indeterminateIndustries = false;
      }else if(n > 0 && n < len){
        this.indeterminateIndustries = true;
      }else if(n == len){
        this.indeterminateIndustries = false
      }
      this.addCircleLayer();
      this.addInventoryLayer();
      this.addInventoryCircleLayer(true);
    },
    changeStations(val){
      let len = this.initData.stations.length;
      let n = val.length;
      if(n == 0){
        this.isCheckedAll = false;
        this.indeterminate = false;
      }else if(n > 0 && n < len){
        this.indeterminate = true;
      }else if(n == len){
        this.indeterminate = false
      }
      this.addCircleLayer();
      this.addInventoryCircleLayer(true);
    },
    handleFilter(){
      this.addCircleLayer();
      this.addInventoryLayer();
      this.addInventoryCircleLayer(true);
    },
    async getList(){
      this.map = this.$parent.map;
      this.removeLayer([
        'air-monitor',
        'live-weather-layer', 
        'live-weather-label', 
        'live-weather-source',
        // 'station-layer',
        // 'circle',
        // 'stations_inventory_' + cityPinyin,
        // 'stations_inventory_circle_'+cityPinyin
      ]);
      await this.getInitData();
      this.addStationLayer();
      this.addCircleLayer();
      this.addInventoryLayer();
      this.addInventoryCircleLayer(true);
    },
    removeLayer(layerIds){
      layerIds.forEach(item => {
        if (this.map.getLayer(item)) this.map.removeLayer(item);
        if (this.map.getSource(item)) this.map.removeSource(item);  
      });      
    },
    addStationLayer(){
      const geojson = {
        type: 'FeatureCollection',
        features: [],
      };
      for (const d of this.initData.stations) {
        geojson.features.push({
          type: 'Feature',
          geometry: {
            type: 'Point',
            coordinates: [d.lon, d.lat]
          },
          properties: d
        });
      }
      if (this.map.getLayer('station-layer')) {
        return;
      }
      const iconUrl = require('@/assets/images/icons/atmosphere-environmental-point-cn-1.png');
      this.map.loadImage(iconUrl, (error, image) => {
        if (error) throw error;
        if (!this.map.hasImage('atmosphere-environmental-point-cn-1')) this.map.addImage('atmosphere-environmental-point-cn-1', image);
        this.map.addLayer({
          id: 'station-layer',
          type: 'symbol',
          source: {
            type: 'geojson',
            data: geojson
          },
          paint: {
            'text-color': '#ff9800',
            'text-halo-color': 'rgb(0,0,0)',
            'text-halo-width': 1,
          },
          layout: {
            'icon-image': 'atmosphere-environmental-point-cn-1',
            'icon-size': .75,
            'icon-allow-overlap': true,
            'icon-ignore-placement': true,
            'text-field': ['get', 'name'],
            'text-anchor': 'bottom',
            'text-offset': [0, -1.5],
            'text-justify': 'auto',
            'text-size': 14,
          }
        });
      });
    },

    addInventoryLayer(isRemove){
      if (this.searchForm.areas !== 0) {
        this.remmoveLayer(this.layer.stations_inventory);
        return;
      }
      if(isRemove){
        this.remmoveLayer(this.layer.stations_inventory);
      }
      if (!this.map) {
        return;
      }
      if (!this.map.getLayer(this.layer.stations_inventory)) {
        this.map.addLayer({
          id: this.layer.stations_inventory,
          source: {
            type: 'geojson',
            data: geoserver + `/hesil/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=hesil:${this.layer.stations_inventory}&outputFormat=application/json`
          },
          type: 'circle',
          paint: {
            'circle-color': [
              'match',
              ['get', 'class'],
              '工业源','#FE5656',
              '扬尘源','#EAEA26',
              '油站油库','#01E17E',
              '大型餐饮','#3DD1F9',
              '#906BF9'
            ],
            'circle-stroke-color': '#000',
            'circle-stroke-width': 1,
            'circle-radius': 5,
          },
        }, this.map.getLayer('station-layer') ? 'station-layer' : undefined);
        this.search(this.layer.stations_inventory);
      } else {
        this.search(this.layer.stations_inventory);
      }
    },

    addInventoryCircleLayer(isRemove){
      if (this.searchForm.areas === 0 || isRemove) {
        this.remmoveLayer(this.layer.stations_inventory_circle);
      }
      if (this.searchForm.areas === 0 || !this.map) {
        return;
      }
      if (!this.map.getLayer(this.layer.stations_inventory_circle)) {
        this.map.addLayer({
          id: this.layer.stations_inventory_circle,
          source: {
            type: 'geojson',
            data: geoserver
              + `/hesil/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=hesil:${this.layer.stations_inventory_circle}&outputFormat=application/json`
              + `&viewparams=km:${this.searchForm.areas};station_list:${this.initData.stationsChecked.join('_')}`
          },
          type: 'circle',
          paint: {
            'circle-color': [
              'match',
              ['get', 'class'],
              '工业源','#FE5656',
              '扬尘源','#EAEA26',
              '油站油库','#01E17E',
              '大型餐饮','#3DD1F9',
              '#906BF9'
            ],
            'circle-stroke-color': '#000',
            'circle-stroke-width': 1,
            'circle-radius': 5,
          },
        }, this.map.getLayer('station-layer') ? 'station-layer' : undefined);
        this.search(this.layer.stations_inventory_circle);
      } else {
        this.search(this.layer.stations_inventory_circle);
      }
    },
    
    addCircleLayer(){
      if (!this.map) {
        return;
      }
      if (this.map.getLayer('station_emis_circle')) {
        this.map.removeLayer('station_emis_circle');
      }
      if (this.map.getSource('station_emis_circle')) {
        this.map.removeSource('station_emis_circle');
      }
      if (this.searchForm.areas === 0) {
        return;
      }
      const data = this.initData.stationsChecked;
      const filter = data.length > 0 ? [
        'match',
        ['get', 'id'],
        data,
        true,
        false
      ] : ['==', 'id', ''];
      this.map.addLayer({
        id: 'station_emis_circle',
        source: {
          type: 'geojson',
          data: geoserver
            + '/hesil/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=hesil:station_emis_circle&outputFormat=application/json'
            + `&viewparams=km:${this.searchForm.areas}`
        },
        type: 'fill',
        paint: {
          'fill-color': '#43a543',
          'fill-opacity': 0.45,
          'fill-outline-color': '#000',
        },
        filter
      }, this.map.getLayer('station-layer') ? 'station-layer' : undefined);
    },

    remmoveLayer(id){
      if (!this.map) {
        return;
      }
      if (this.map.getLayer(id)) {
        this.map.removeLayer(id);
      }
      if (this.map.getSource(id)) {
        this.map.removeSource(id)
      }
    },
    getComponentsName(data){
      let name;
      switch(data){
        case '工业源':
          name = 'editIndustry';
          break;
        case '扬尘源':
          name = 'editDust';
          break;
        case '油站油库':
          name = 'editOil';
          break;
        case '大型餐饮':
          name = 'editRestaurant';
          break;
      }
      return name;
    },
    search(layerId) {
      if (!layerId) {
        layerId = this.map.getLayer(this.layer.stations_inventory)
        ? this.layer.stations_inventory
        : this.layer.stations_inventory_circle
      }
      const waiting = setInterval(() => {
        if (!layerId || !this.map.getLayer(layerId)) {
          clearInterval(waiting);
          return;
        }
        const sourced = this.map.isSourceLoaded(layerId);
        if (sourced) {
          clearInterval(waiting);
          const res = this.map.querySourceFeatures(layerId);
          let arr = res.filter(i => i.properties && this.searchForm.class.indexOf(i.properties.class) != -1);
          if(this.searchForm.industries.length == 0){
            arr = arr.filter(i => i.properties.class != '工业源')
          }else{
            arr = arr.filter(i => {
              return (i.properties.class == '工业源' && this.searchForm.industries.indexOf(i.properties.indtype_level2) != -1) || i.properties.class != '工业源';
            });
          }
          if(this.searchForm.searchText){
            arr = arr.filter(i => i.properties.name.indexOf(this.searchForm.searchText) > -1);
          }
          if(this.searchForm.county != '全市'){
            arr = arr.filter(i => i.properties.county == this.searchForm.county);
          };
          const names = Array.from(new Set(arr.map(i => i.properties.name)));
          const filter1 = names.length > 0 ? [
            'match',
            ['get', 'name'],
            names,
            true,
            false
          ] : ['==', ['get', 'name'], null];
          this.map.setFilter(layerId, ['all',  filter1]);
          this.addPopup(layerId);
        }
      }, 200);
    },
    addPopup(layerId){
        const popup = new mapboxgl.Popup({
            closeButton: false,
            closeOnClick: false
        });
        this.map.on('mouseenter', layerId, (e) => {
            this.map.getCanvas().style.cursor = 'pointer';
            const coordinates = e.features[0].geometry.coordinates.slice();
            while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
                coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
            }
            const prop = e.features[0].properties;
            let html = `<div class="map-popup-container">`;
            html += `<div class="popup-title">污染排放</div>`;
            html += '<div class="popup-content"><table class="popup-table">';
            html += `<tr><td>企业名称</td><td>${prop.name}</td></tr>`;
            html += `<tr><td>所属区县</td><td>${prop.county}</td></tr>`;
            html += `<tr><td>污染源类别</td><td>${prop.class}</td></tr>`;
            html += `<tr><td>国民经济行业类型（2级）</td><td>${prop.indtype_level2}</td></tr>`;
            html += '</table></div>'
            html += '</div>';
            popup.setLngLat(coordinates)
                .setHTML(html)
                .addTo(this.map);
        });
        this.map.on('mouseleave', layerId, () => {
            this.map.getCanvas().style.cursor = '';
            popup.remove();
        });
    }
  }
}
</script>


